package com.example.shopping.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.alibaba.fastjson.JSON;
import com.example.shopping.common.consts.ResultEnum;
import com.example.shopping.common.response.RestResponse;
import com.example.shopping.dao.OrderDao;
import com.example.shopping.pojo.domain.OrderBean;
import com.example.shopping.pojo.domain.OrderDetailsBean;
import com.example.shopping.service.OrderDetailsService;
import com.example.shopping.service.OrderService;
import com.example.shopping.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author Dream
 * @version 1.0
 * @date 2020/11/9 18:44
 */
@RestController
@RequestMapping(value="order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderDetailsService orderDetailsService;
    /**
     * 查询订单
     * @param userXh
     * @return
     */
    @RequestMapping(value="/getAll")
    public RestResponse getAll(@RequestParam(value="userXh") String userXh){
        return new RestResponse(ResultEnum.SUCCESS,orderService.getByXh(userXh));
    }


    /**
     *
     * @param map
     * @return
     */
    @RequestMapping(value="/addOrder")
    public RestResponse addOrder(@Validated @RequestBody HashMap<String,Object> map){
        //map转字符串再转实体类
        OrderBean orderBean= JsonUtil.decode(JSON.toJSONString(map.get("order")),OrderBean.class);
        //map转字符串再转 array JsonUtil.decode(jsonArray.toString(), new TypeReference<List<MovieEntity>>() {});
        List<OrderDetailsBean> details=JsonUtil.decode(JSON.toJSONString(map.get("details")),new TypeReference<List<OrderDetailsBean>>() {});
        //加入订单
        String message=orderService.addOrder(orderBean);
        List<OrderBean> list=orderDao.getByXh(orderBean.getUserXh());
        OrderBean orderBean1=list.get(0);
        //加入订单详情
        orderDetailsService.addDetails(details,orderBean1.getId());
        return new RestResponse(ResultEnum.SUCCESS,message);
    }
}
